package tk.xboot.boot.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@RestController
public class SSEController {

    @GetMapping("push/sse")
    public void ssePush(HttpServletResponse response) throws IOException {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");
        Random r = new Random();
        boolean run = true;
        System.out.println(Thread.currentThread().getId());

        int i = 0;
        PrintWriter pw = response.getWriter();
        while (run) {
            try {
                var rtn = "id:"+ ++i +"\nevent:evt\ndata:{\"val\":" + r.nextInt() +"}\n\n";
                Thread.sleep(500);
                pw.write(rtn);
                run = ! pw.checkError();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

